﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KBVault.Web.Infrastructure;
using KBVault.DAL.Repository;
using KBVault.DAL.Entities;

namespace KBVault.Web.Public
{
    public partial class ShowTag : KBVaultPublicPage
    {        
   

        private void DoSearch( string tag, int page = 1)
        {
            if (String.IsNullOrEmpty(tag))
            {
                return;
            }

            try
            {
                SetPageTitle("Listing articles with Tag \"" + tag + "\"");
                List<Article> articles = TagRepository.GetArticlesWithTag(tag, page, 10);
                if (articles.Count > 0)
                {
                    rptArticles.DataSource = articles;
                    rptArticles.DataBind();
                }
                if (TagRepository.GetArticleCountWithTag(tag) > 0)
                {
                    paginator.CurrentPage = page;
                    paginator.MaxPage = (int)Math.Ceiling(TagRepository.GetArticleCountWithTag(tag) / 10.0);
                    paginator.HrefMask = "/Public/ShowTag.aspx?Tag=" + HttpUtility.UrlEncode(tag) + "&Page={0}";
                    paginator.BindPaginator();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);                
            }

        }
        protected new void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            string tagName="";
            int page=1;
            
            if (Request.QueryString["Tag"] != null)
            {
                tagName = HttpUtility.UrlDecode(Request.QueryString["Tag"]);
                TagHeader.Text = tagName;      
            }
            if (Request.QueryString["Page"] != null)
            {
                try
                {
                    page = Convert.ToInt32(Request.QueryString["Page"]);
                }
                catch (Exception)
                {
                    page = 1;
                }
                
            }
            DoSearch(tagName,page);
        }
    }
}